<template>
  <!-- 搜索框 -->
  <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
    <el-form-item label="文章标题">
      <el-input v-model="queryInfo.articleName" placeholder="请输入标题名" clearable />
    </el-form-item>
    <el-form-item label="文章类型">
      <el-select v-model="queryInfo.typeId" placeholder="请选择文章类型" clearable>
        <el-option v-for="type in articleTypeList" :key="type.id" :label="type.name" :value="type.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="咨询师">
      <el-select v-model="queryInfo.consultId" placeholder="请选择咨询师" clearable>
        <el-option v-for="consult in consultList" :key="consult.id" :label="consult.name"
          :value="consult.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getList">搜索</el-button>
    </el-form-item>
    <div>
      <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
    </div>
  </el-form>
  <!-- 信息展览 -->
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="id" label="id" width="50" />

    <el-table-column prop="articleName" label="文章标题" width="120" />
    <el-table-column prop="articleIntroduce" label="文章简介" width="120">
      <template #default="scope">
        <div class="ellipsis-text">{{ scope.row.articleIntroduce }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="consult.name" label="咨询师" width="100" />
    <el-table-column prop="tabularChart" label="文章封面" width="120">
      <template #default="scope">
        <el-image v-if="scope.row.tabularChart" style="width: 100px; height: 100px" :src="url + scope.row.tabularChart"
          :fit="fit" />
      </template>
    </el-table-column>
    <el-table-column label="详情内容" width="120">
      <template #default="scope">
        <div class="ellipsis-text">{{ scope.row.details }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="readQuantity" label="阅读量" width="100" />
    <el-table-column prop="collects" label="收藏量" width="100" />
    <el-table-column prop="articleType.name" label="文章类型" width="100" />
    <el-table-column prop="createTime" label="创建时间" width="120" />
    <el-table-column fixed="right" label="操作" min-width="200">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="toView(scope.row)">查看详情内容</el-button>
        <el-button link type="primary" size="small" @click="toEdit(scope.row)">修改</el-button>
        <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <el-pagination style="margin-top: 10px;" v-model:current-page="queryInfo.pageNum"
    v-model:page-size="queryInfo.pageSize" :page-sizes="[1, 5, 10, 20]" size="default" background="false"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
  <!-- 添加编辑弹框 -->
  <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
    <el-form :model="article">
      <el-form-item label="文章标题">
        <el-input v-model="article.articleName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="文章简介">
        <el-input v-model="article.articleIntroduce" autocomplete="off" />
      </el-form-item>
      <el-form-item label="咨询师名">
        <el-select v-model="article.consultId" placeholder="请选择咨询师">
          <el-option v-for="consult in consultList" :key="consult.id" :label="consult.name"
            :value="consult.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面">
        <el-upload v-model:file-list="fileList" class="avatar-uploader" list-type="picture-card"
          action="http://localhost:8080/file/upload" :on-success="handleAvatarSuccess">
          <img v-if="tabularChart" :src="tabularChart" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章详情">
        <TEditor :modelValue="article.details" @update:modelValue="modelValue"></TEditor>
      </el-form-item>
      <el-form-item label="阅读数量">
        <el-input v-model="article.readQuantity" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收藏数量">
        <el-input v-model="article.collects" autocomplete="off" />
      </el-form-item>
      <el-form-item label="文章类型">
        <el-select v-model="article.typeId" placeholder="请选择文章类型">
          <el-option v-for="type in articleTypeList" :key="type.id" :label="type.name" :value="type.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input v-model="article.createTime" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate">
          {{ saveOrUpdateTitle }}
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 详情内容弹出框 -->
  <el-dialog v-model="viewVisible" :title="viewTitle" width="500">
    <el-form-item label="文章详情">
      <TEditor :modelValue="viewArticle.details" @update:modelValue="modelValue" readonly :toolbar="false"></TEditor>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeView">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import TEditor from '@/components/TEditor.vue';
import { Plus } from '@element-plus/icons-vue';

// 富文本
const modelValue = (value) => {
  console.log('value', value);
  article.value.details = value;
};


// 图片上传
const tabularChart = ref('')
const fileList = ref([])

// 图片上传
const handleAvatarSuccess = (response, uploadFile) => {
  tabularChart.value = URL.createObjectURL(uploadFile.raw)
  // 上传成功，则需要把返回的数据复制给article.tabularChart
  article.value.tabularChart = response.data
}

// 修改或添加
const saveOrUpdateVisible = ref(false)
const article = ref({
  id: '',
  articleName: '',
  articleIntroduce: '',
  consultId: '',
  tabularChart: '',
  details: '',
  readQuantity: '',
  collects: '',
  typeId: '',
  createTime: ''
})
const saveOrUpdateTitle = ref('添加')

// 文章类型列表
const articleTypeList = ref([])
// 咨询师列表
const consultList = ref([])

// 详情弹出框相关
const viewVisible = ref(false)
const viewTitle = ref('文章详情')
const viewArticle = ref({
  details: ''
})

// 获取文章类型列表
const getArticleTypeList = () => {
  axios.get('/articleType/selectAll')
    .then(resp => {
      let result = resp.data
      if (result.code == 1) {
        articleTypeList.value = result.data.list
        console.log(articleTypeList.value);
      } else {
        ElMessage.error('获取文章类型列表失败')
      }
    })
}

// 获取咨询师列表
const getConsultList = () => {
  axios.get('/consult/selectAll')
    .then(resp => {
      let result = resp.data
      if (result.code == 1) {
        consultList.value = result.data.list
        console.log(consultList.value);
      } else {
        ElMessage.error('获取咨询师列表失败')
      }
    })
}

// 去修改的界面
const toEdit = (row) => {
  saveOrUpdateTitle.value = '修改'
  saveOrUpdateVisible.value = true
  article.value = { ...row }
  console.log(article.value);
  // 把图片的名称和路径放入到fileList中
  fileList.value = [
    {
      url: url.value + article.value.tabularChart,
      name: '000'
    }
  ]
}

// 去添加的界面
const toAdd = () => {
  saveOrUpdateTitle.value = '添加'
  saveOrUpdateVisible.value = true
  article.value = {
    id: '',
    articleName: '',
    articleIntroduce: '',
    consultId: '',
    tabularChart: '',
    details: '',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: ''
  }
}

// 取消修改或保存
const close = () => {
  saveOrUpdateVisible.value = false
  // 请求图片展示
  tabularChart.value = ''
  fileList.value = []
  // 清空表单
  article.value = {
    id: '',
    articleName: '',
    articleIntroduce: '',
    consultId: '',
    tabularChart: '',
    details: '',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: ''
  }
}

// 保存或修改
const saveOrUpdate = () => {
  if (saveOrUpdateTitle.value === '添加') {
    //调用后端接口添加
    axios.post('/article', article.value)
      .then((resp) => {
        let result = resp.data
        if (result.code === 1) {
          // 重新获取列表
          getList()
          ElMessage.success('添加文章成功')
          saveOrUpdateVisible.value = false
        } else {
          ElMessage.error('添加文章失败')
        }
      })
  } else {
    //调用后端接口修改
    axios.put('/article', article.value)
      .then(resp => {
        let result = resp.data
        if (result.code === 1) {
          // 重新获取列表
          getList()
          ElMessage.success('修改文章成功')
          saveOrUpdateVisible.value = false
        } else {
          ElMessage.error('修改文章失败')
        }
      })
  }
  // 关闭弹框
  saveOrUpdateVisible.value = false
  // 请求图片展示
  tabularChart.value = ''
  // 清空表单
  article.value = {
    id: '',
    articleName: '',
    articleIntroduce: '',
    consultId: '',
    tabularChart: '',
    details: '',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: ''
  }
}

// 定义一个图片路径
const url = ref('http://localhost:8080/file/downLoad?fileName=')
// 定义一个图片缩放
const fit = ref('cover')

const tableData = ref([])
//   定义一个方法当页面加载时就调用
onMounted(() => {
  getList()
  getArticleTypeList()
  getConsultList()
})
//   定义一个全局参数变量
const queryInfo = ref({
  pageNum: 1,
  pageSize: 5,
  id: '',
  articleName: '',
  articleIntroduce: '',
  consultId: '',
  tabularChart: '',
  details: '',
  readQuantity: '',
  collects: '',
  typeId: '',
  createTime: ''
})
// 定义一个数据总条数
const total = ref(0)
//   定义一个方法，用于获取文章列表
const getList = () => {
  // 使用axios调用后端接口获取数据
  axios.get('/article/selectAll', {
    params: queryInfo.value
  })
    .then((resp) => {
      let result = resp.data // 后端返回的数据
      if (result.code === 1) {
        total.value = result.data.total
        tableData.value = result.data.list
      } else {
        ElMessage.error('获取文章列表失败')
      }
    })
}
// 分页
const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getList();
}
const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getList();
}

// 删除
const onDel = (id) => {
  ElMessageBox.confirm(
    '真的要删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //调用后端接口删除
      axios.delete('/article/' + id)
        .then((resp) => {
          let result = resp.data
          if (result.code === 1) {
            // 重新获取列表
            getList()
            ElMessage.success('删除成功')
            getList()
          } else {
            ElMessage.error('删除失败')
          }
        })
    })
    .catch(() => { })
}

// 查看详情
const toView = (row) => {
  viewTitle.value = '文章详情'
  viewVisible.value = true
  viewArticle.value = { ...row }
}

// 关闭详情弹出框
const closeView = () => {
  viewVisible.value = false
  viewArticle.value = {
    details: ''
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.ellipsis-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  /* 根据表格列宽调整 */
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px solid black;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>